package com.orangelife.mobile.tehui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.jump.OrderJumper;
import com.common.jump.WebJumper;
import com.common.util.OrangePhoneUtil;
import com.curry.android.util.CountDownHMSHandler;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.activities.adapter.ActivityDetailListViewAdapter;
import com.orangelife.mobile.activities.biz.InnerListView;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.WebViewURL;
import com.orangelife.mobile.individual.activity.MyOrderDetailActivity;
import com.orangelife.mobile.shoppingcart.activity.ShoppingCartActivity;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.orangelife.mobile.surrounding.activity.SelectedStandardActivity;
import com.thirdsdk.umeng.UmShareBiz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.widget.MyScrollview;
import com.orangelife.mobile.web.WebWin;
import com.umeng.socialize.media.UMImage;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 特惠商品详情
 */
public class TehuiDetailActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_title_call)
    ImageView ivTitleCall;
    @Bind(R.id.iv_title_shopping_cart)
    ImageView ivShoppingCart;
    @Bind(R.id.tvGoodNumber)
    TextView tvGoodNumber;
    @Bind(R.id.flShoppingCart)
    FrameLayout flShoppingCart;
    @Bind(R.id.ivBigPhoto)
    ImageView ivBigPhoto;
    @Bind(R.id.tvGoodsName)
    TextView tvGoodsName;
    @Bind(R.id.ibShare)
    ImageButton ibShare;
    @Bind(R.id.tvSelectStandard)
    TextView tvSelectStandard;
    @Bind(R.id.tvCommercialTnantName)
    TextView tvCommercialTnantName;
    @Bind(R.id.tvGoodsDetail)
    TextView tvGoodsDetail;
    @Bind(R.id.wwPhoto)
    WebWin wwPhoto;
    @Bind(R.id.tvBuyPriceDiscount)
    TextView tvBuyPriceDiscount;
    @Bind(R.id.tvBuyPrice)
    TextView tvBuyPrice;
    @Bind(R.id.tvAddShoppingCart)
    TextView tvAddShoppingCart;
    @Bind(R.id.tvBuy)
    TextView tvBuy;
    @Bind(R.id.lvConsumerTips)
    InnerListView lvConsumerTips;
    @Bind(R.id.slSlide)
    MyScrollview slSlide;
    @Bind(R.id.llTitle)
    LinearLayout llTitle;
    @Bind(R.id.ib_back)
    ImageButton ibBack;
    @Bind(R.id.ivTiantian)
    ImageView ivTiantian;
    @Bind(R.id.tvMoney)
    TextView tvMoney;
    @Bind(R.id.ivBaoyou)
    ImageView ivBaoyou;
    @Bind(R.id.tvTipTime)
    TextView tvTipTime;
    @Bind(R.id.tvHour)
    TextView tvHour;
    @Bind(R.id.tvMinute)
    TextView tvMinute;
    @Bind(R.id.tvSecond)
    TextView tvSecond;
    @Bind(R.id.tvJifenTip)
    TextView tvJifenTip; //赠送积分
    @Bind(R.id.zeng)
    TextView zeng; //赠送积分
    @Bind(R.id.llTehuiBg)
    LinearLayout llTehuiBg;
    @Bind(R.id.tvGoodsZeng)
    TextView tvGoodsZeng;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.tvRMB)
    TextView tvRMB;
    private float alpha = 0.0f;
    /**
     * list传过来的数据
     */
    private Map<String, Object> map;

    /**
     * 服务端接收过来的数据
     */
    private Map<String, Object> mapDetail;
    /**
     * 分享图片
     */
    @SuppressWarnings("unused")
    private UMImage umengImage;
    /**
     * 分享title
     */
    private String uMtitle = "";
    /**
     * 分享content
     */
    private String uMcontent = "";

    private List<Map<String, Object>> listSummary = null;

    private List<Map<String, Object>> listProduct = null;

    /**
     * 图片下载
     */
    private ImageDownloader image = ImageDownloader.getImageDownloader();
    private CountDownHMSHandler countDownHandler;

    private String merId;
    private String activityGoodsID = "";
    private String pRuleID;
    private String activityID = "";
    private int status;
    private int defaltTime = 61;
    private boolean isRefresh;
    UmShareBiz shareBiz;
    private static final int REQUEST_SELECT_STANDARD = 888;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tehui_detail);
        ButterKnife.bind(this);

        shareBiz = new UmShareBiz(this);
        findView();
        setScroll();
        setListener();
    }

    private void setListener() {
        emptyLayout.setOnLayoutClickListener(listener);
    }


    private void setScroll() {
        llTitle.getBackground().setAlpha(0);
        //设置标题栏活动透明效果
        slSlide.setScrollListener(new MyScrollview.ScrollViewListener() {
            @Override
            public void scorlling(int scrollY, int oldScrollY) {
                int alphaNow = 255;
                alphaNow = (int) (scrollY < 200 ? alphaNow * (scrollY / 200.0f) : 255);
                llTitle.getBackground().setAlpha(alphaNow);
                if (alphaNow > 200) {
                    ibBack.setBackgroundResource(R.drawable.back_orange);
                    ivTitleCall.setBackgroundResource(R.drawable.icon_phone);
                    ivShoppingCart.setBackgroundResource(R.drawable.icon_shoppingcar);
                } else {
                    ibBack.setBackgroundResource(R.drawable.ic_shadow_back);
                    ivTitleCall.setBackgroundResource(R.drawable.ic_shadow_phone);
                    ivShoppingCart.setBackgroundResource(R.drawable.ic_shadow_cart);
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getGoodsNumber() == 0) {
            tvGoodNumber.setVisibility(View.GONE);
        } else {
            tvGoodNumber.setVisibility(View.VISIBLE);
            tvGoodNumber.setText(getGoodsNumber() + "");
        }

        BLog.getInstance().inMerDetail(id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownHandler != null)
            countDownHandler.stopTimer();
        BLog.getInstance().outMerDetail(id);
    }

    /***
     * 赋值
     */
    private void findView() {
        ExitApplication.getInstance().addPaidActivity(this);
        id = getIntent().getStringExtra("id");
        tvRMB.setText(Constant.RMB_FLAG);
        tv1.setText(Constant.RMB_FLAG);
        tvTitle.setText(R.string.trade_detail);
        ivTitleCall.setOnClickListener(listener);
        flShoppingCart.setOnClickListener(listener);
        tvSelectStandard.setOnClickListener(listener);
        tvBuy.setOnClickListener(listener);
        tvAddShoppingCart.setOnClickListener(listener);
        ivTiantian.setOnClickListener(listener);
        ibShare.setOnClickListener(listener);
        tvJifenTip.setOnClickListener(listener);
        getActivityDetail();
    }


    /**
     * 开启倒计时
     */
    private void startTimeDown() {
        if (countDownHandler == null) {
            countDownHandler = new CountDownHMSHandler(tvHour, tvMinute, tvSecond, 0);
            countDownHandler.setOnCountDownTimerFinishedListener(new CountDownHMSHandler.OnCountDownTimerFinishedListener() {
                @Override
                public void onFinish() {
                    if (!isRefresh) {
                        getDataFromServer();
                        getActivityDetail();
                        isRefresh = true;
                    }
                }

                @Override
                public void onCountDown(int h, int m, int s) {
                }

            });
            countDownHandler.startTimer(defaltTime);
        } else {
            //重新开始倒计时
            countDownHandler.stopTimer();
            countDownHandler = null;
            startTimeDown();
        }
    }

    private int getGoodsNumber() {
        return ShoppingCartBiz.getGoodsCount();
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 行为采集使用ID
     */
    String id = null;

    /**
     * 获得详情
     */
    @SuppressWarnings("deprecation")
    private void getActivityDetail() {
        TeHuiBiz.getTehuiDataDetail(id, handler);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.emptyLayout:
                    getActivityDetail();
                    break;
                case R.id.tvJifenTip:
                    WebJumper.jumpToJifenGongFang(TehuiDetailActivity.this);
                    break;
                case R.id.iv_title_call:
                    OrangePhoneUtil.callCustomerService2(TehuiDetailActivity.this);
                    break;
                case R.id.flShoppingCart:
                    /*跳转购物车页面*/
                    IntentHelper.getInstances().getIntent(TehuiDetailActivity.this, ShoppingCartActivity.class);
                    break;
                case R.id.ibShare:
                    shareBiz.share(uMtitle, uMcontent, WebViewURL.TEHUI_SHARE, activityID);
                    break;
                case R.id.tvSelectStandard://选择规格
                    if (mapDetail != null) {
                        ExitApplication.getInstance().addFailActivity(TehuiDetailActivity.this);
                        OrderJumper.jumpToSelectStandard(TehuiDetailActivity.this,REQUEST_SELECT_STANDARD,position,limiteNum,status,mapDetail);
                    }
                    break;
                case R.id.tvAddShoppingCart://加入购物车
                    if (mapDetail != null) {
                        ExitApplication.getInstance().addFailActivity(TehuiDetailActivity.this);
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.putExtra("position", position);
                        intent.putExtra("flag", 2);
                        bundle.putSerializable("specification",
                                (Serializable) mapDetail);
                        intent.putExtras(bundle);
                        intent.setClass(TehuiDetailActivity.this,
                                SelectedStandardActivity.class);
                        startActivityForResult(intent, REQUEST_SELECT_STANDARD);
                    }
                    break;
                case R.id.tvBuy://购买
                    if (mapDetail != null) {
                        ExitApplication.getInstance().addFailActivity(TehuiDetailActivity.this);
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.putExtra("position", position);
                        intent.putExtra("flag", 3);
                        bundle.putSerializable("specification",
                                (Serializable) mapDetail);
                        intent.putExtra("isTehui", true);
                        intent.putExtra("limiteNum", limiteNum);
                        intent.putExtra("tehuiStatus", status);
                        intent.putExtra("activityGoodsID", activityGoodsID);
                        intent.putExtras(bundle);
                        intent.setClass(TehuiDetailActivity.this,
                                SelectedStandardActivity.class);
                        startActivityForResult(intent, REQUEST_SELECT_STANDARD);
                    }
                    break;
                case R.id.ivTiantian://特惠活动
                    Bundle bundle = new Bundle();
                    if (StringUtil.isBlank(activityID)) {
                        return;
                    }
                    bundle.putString("id", activityID);
                    IntentHelper.getInstances().bundleWithExtra(TehuiDetailActivity.this, TehuiActivity.class, bundle);
                    finish();
                    break;
                default:
                    break;
            }

        }
    };

    private int position;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_STANDARD && resultCode == RESULT_OK) {
            if (data != null) {
                //设置选择的规格
                position = data.getIntExtra("position", 0);
                setProduct(listProduct.get(position));
            }
        }
    }

    /***
     * 设置详情
     */
    private void setDetail() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = width * 11 / 16;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
        ivBigPhoto.setLayoutParams(params);
        merId = String.valueOf(mapDetail.get("goodsID"));
        uMtitle = String.valueOf(mapDetail.get("goodsName"));
        uMcontent = String.valueOf(mapDetail.get("goodsBrief"));
        tvGoodsName.setText(String.valueOf(mapDetail.get("goodsName")));
//        tvCommercialTnantName.setText(String.valueOf(mapDetail.get("merchantName")));
        tvCommercialTnantName.setText("橙子配送");
        String summary = String.valueOf(mapDetail.get("summary"));
        lvConsumerTips.setFocusable(false);
        if (!StringUtil.isBlank(summary)) {
            listSummary = (List<Map<String, Object>>) mapDetail.get("summary");
            ActivityDetailListViewAdapter adapter = new ActivityDetailListViewAdapter(
                    this, listSummary);
            lvConsumerTips.setAdapter(adapter);

        }
        tvGoodsDetail.setText(String.valueOf(mapDetail.get("goodsDesc")));
        listProduct = (List<Map<String, Object>>) mapDetail.get("products");
        if (listProduct != null && listProduct.size() > 0) {
            setProduct(listProduct.get(0));
        } else {
            tvJifenTip.setVisibility(View.GONE);
            zeng.setVisibility(View.GONE);
        }
        image.download(String.valueOf(mapDetail.get("goodsLogo")).trim(), ivBigPhoto,
                ImageDownloader.ImageSize.IMAGE_SIZE_MIDDLE_JPG);
        Map<String, Object> actMap = new HashMap<>();
        actMap = (Map<String, Object>) mapDetail.get("activityGoods");
        setActivityData(actMap);
        setWebView();
    }

    private void setProduct(Map<String, Object> product) {
        tvBuyPriceDiscount.setText(String.valueOf(product.get("price")));
        tvBuyPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvBuyPrice.setText("¥" + String.valueOf(product.get("mkPrice")));
        String points = String.valueOf(product.get("points"));//'赠送积分'
        String deduction = String.valueOf(product.get("deduction"));//--'可抵扣百分比'
        String pdtDesc = String.valueOf(product.get("pdtDesc"));//规格
        pRuleID = String.valueOf(product.get("pRuleID"));//规格
        zeng.setVisibility(View.VISIBLE);
        tvGoodsZeng.setText("橙汁最高抵扣" + deduction + "%");
        tvJifenTip.setText(points + "ml橙汁");
        tvSelectStandard.setText(pdtDesc);
    }

    int limiteNum;//可购买最大数量

    /**
     * 设置特惠活动信息
     *
     * @param map
     */
    private void setActivityData(Map<String, Object> map) {
        String startTime = String.valueOf(map.get("startTime"));
        String potoUrl = String.valueOf(map.get("potoUrl"));
        status = Integer.parseInt(String.valueOf(map.get("status")));
        String remak = String.valueOf(map.get("remak"));
        String activityNumber = String.valueOf(map.get("activityNumber"));
        String endTime = String.valueOf(map.get("endTime"));
        String activityName = String.valueOf(map.get("activityName"));
        activityID = String.valueOf(map.get("activityID"));
        String activityPrice = String.valueOf(map.get("activityPrice"));//活动价格
        String stockNumberNew = String.valueOf(map.get("stockNumberNew"));//销售后库存数量
        String purchaseNumber = String.valueOf(map.get("purchaseNumber"));//活动限购数量
        String userPayNumber = String.valueOf(map.get("userPayNumber"));//用户已购数量
        tvMoney.setText(activityPrice);
        if (StringUtil.isBlank(stockNumberNew)) {
            stockNumberNew = "0";
        }
        if (StringUtil.isBlank(userPayNumber)) {
            userPayNumber = "0";
        }
        if (StringUtil.isBlank(purchaseNumber)) {
            purchaseNumber = "0";
        }

        int residue = Integer.parseInt(stockNumberNew);
        if (status == 1 && residue <= 0) {
            tvSelectStandard.setEnabled(false);
            tvBuy.setEnabled(false);
            tvBuy.setBackgroundColor(getResources().getColor(R.color.text_grey));
        }
        String num = DecimalUtil.subtract(purchaseNumber, userPayNumber);
        limiteNum = Math.min(residue, Integer.parseInt(num));
        activityGoodsID = String.valueOf(map.get("activityGoodsID"));
        defaltTime = (int) Double.parseDouble(String.valueOf(map.get("leftTime")));
        startTimeDown();
        if (status == 0) {
            llTehuiBg.setBackgroundColor(this.getResources().getColor(R.color.deep_green));
            tvTipTime.setText(this.getResources().getString(R.string.activity_time_tip_start1));
        } else if (status == 1) {
            llTehuiBg.setBackgroundColor(this.getResources().getColor(R.color.deep_red));
            tvTipTime.setText(this.getResources().getString(R.string.activity_time_tip_end1));
            tvAddShoppingCart.setVisibility(View.GONE);
        } else if (status == 2) {
            tvTipTime.setText("活动已结束");
            llTehuiBg.setBackgroundColor(this.getResources().getColor(R.color.deep_green));
            tvAddShoppingCart.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 设置照片的webview
     */
    private void setWebView() {
        String pics = String.valueOf(mapDetail.get("goodsImgs"));
        wwPhoto.loadDataWithBaseURL(pics);
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            Log.e("特惠", msg.obj.toString());
            switch (msg.what) {
                case 15:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    String orderID = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("orderID").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        finish();
                        ToastHelper.getInstance()._toast(
                                getResources().getString(R.string.submit_success));
//                        if(type == 2){
//                            return;
//                        }
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        Map<String, Object> mapOrder = new HashMap<String, Object>();
                        mapOrder.put("orderID", orderID);
//                        mapOrder.put("orderType", type);
                        bundle.putSerializable("map", (Serializable) mapOrder);
                        intent.setClass(TehuiDetailActivity.this,
                                MyOrderDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaintes_sumbite_fail));
                    }
                    break;
                case TeHuiBiz.GET_TEHUI_DETAIL:
                    emptyLayout.dismiss();
                    DialogHelper.closeDialog(dialog);
                    mapDetail = new HashMap<>();
                    Map<String, Object> map = JSONHelper.jsonToMap(msg.obj.toString());
                    if (!map.get("entity").toString().equals("")) {
                        mapDetail = (Map<String, Object>) map.get("entity");
                        if (mapDetail == null || mapDetail.size() == 0) {
                            ToastHelper.getInstance().displayToastWithQuickClose("获取数据失败");
                            emptyLayout.setErrorType(EmptyLayout.NODATA);
                            return;
                        }
                        setDetail();
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    break;
                case 500:
                    emptyLayout.setErrorType(EmptyLayout.NODATA);
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog, TehuiDetailActivity.this);
                    break;
                case 15001:
                    ToastHelper.getInstance()._toast(
                            getResources().getString(R.string.goods_undercarriage));
                    tvBuy.setEnabled(false);
                    break;
                default:
                    break;
            }
        }

    };


}

